<?php
// 显示所有错误
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 需要修复的文件列表
$files = [
    'index.php',
    'users.php',
    'games.php',
    'achievements.php',
    'stats.php',
    'settings.php',
    'user_detail.php',
    'user_edit.php',
    'game_edit.php',
    'user_game_records.php',
    'user_achievements.php'
];

$results = [];
$success = true;

// 检查PHP文件语法
function checkPhpSyntax($filePath) {
    $output = [];
    $return_var = 0;
    
    // 使用PHP命令来检查语法
    exec('php -l "' . $filePath . '" 2>&1', $output, $return_var);
    
    if ($return_var !== 0) {
        return ['valid' => false, 'error' => implode("\n", $output)];
    }
    
    return ['valid' => true];
}

// 备份文件
function backupFile($filePath) {
    $backupPath = $filePath . '.bak.' . date('YmdHis');
    if (copy($filePath, $backupPath)) {
        return $backupPath;
    }
    return false;
}

foreach ($files as $file) {
    $filePath = __DIR__ . '/' . $file;
    
    if (file_exists($filePath)) {
        // 备份文件
        $backup = backupFile($filePath);
        if ($backup) {
            $results[] = "已备份文件 {$file} 到 " . basename($backup);
        }
        
        $content = file_get_contents($filePath);
        
        // 检查是否已经包含 DatabaseHelper.php
        if (strpos($content, "require_once 'includes/DatabaseHelper.php'") === false) {
            // 添加 DatabaseHelper.php 的引用
            $newContent = preg_replace(
                '/(require_once\s+\'includes\/[^\']+\';(\s*\/\/[^\n]*)?(\s*\n)*)/', 
                "$1require_once 'includes/DatabaseHelper.php';\n\n", 
                $content, 
                1
            );
            
            if ($newContent !== $content) {
                file_put_contents($filePath, $newContent);
                
                // 检查语法
                $syntaxCheck = checkPhpSyntax($filePath);
                if ($syntaxCheck['valid']) {
                    $results[] = "已在 {$file} 中添加 DatabaseHelper.php 引用";
                } else {
                    // 恢复备份
                    copy($backup, $filePath);
                    $results[] = "无法修改 {$file}：语法错误，已恢复备份";
                    $success = false;
                }
            } else {
                // 尝试在文件开头添加
                $newContent = "<?php\n// 引入数据库帮助类\nrequire_once 'includes/DatabaseHelper.php';\n\n" . substr($content, 5);
                file_put_contents($filePath, $newContent);
                
                // 检查语法
                $syntaxCheck = checkPhpSyntax($filePath);
                if ($syntaxCheck['valid']) {
                    $results[] = "已在 {$file} 开头添加 DatabaseHelper.php 引用";
                } else {
                    // 恢复备份
                    copy($backup, $filePath);
                    $results[] = "无法修改 {$file}：语法错误，已恢复备份";
                    $success = false;
                }
            }
        } else {
            $results[] = "{$file} 已包含 DatabaseHelper.php 引用，无需修改";
        }
    } else {
        $results[] = "文件 {$file} 不存在，已跳过";
    }
}

// 检查 header.php 中是否包含 DatabaseHelper.php
$headerFile = __DIR__ . '/includes/header.php';
if (file_exists($headerFile)) {
    // 备份文件
    $backup = backupFile($headerFile);
    if ($backup) {
        $results[] = "已备份文件 header.php 到 " . basename($backup);
    }
    
    $content = file_get_contents($headerFile);
    
    // 检查是否已经包含DatabaseHelper
    if (strpos($content, "require_once __DIR__ . '/DatabaseHelper.php'") === false) {
        $results[] = "修改 header.php 以支持 DatabaseHelper";
        
        // 在管理员验证部分之前添加DatabaseHelper引用
        $pattern = "/\/\/ 获取当前管理员信息.*?\\\$admin = null;.*?if \(\\\$isLoggedIn\) {/s";
        if (preg_match($pattern, $content, $matches)) {
            $replacement = $matches[0] . "\n    // 获取数据库连接\n    require_once __DIR__ . '/DatabaseHelper.php';\n    \$db = Database::getInstance();\n    \n    // 获取用户信息\n    \$stmt = \$db->query(\"SELECT * FROM \" . DB_PREFIX . \"users WHERE id = ? AND role = 'admin'\", [\$_SESSION['admin_user_id']]);\n    \$admin = \$stmt->fetch();\n    \n    // 如果用户不存在或不是管理员，注销会话\n    if (!\$admin) {\n        unset(\$_SESSION['admin_user_id']);\n        unset(\$_SESSION['admin_username']);\n        header('Location: login.php');\n        exit;\n    }";
            
            $newContent = preg_replace($pattern, $replacement, $content);
            
            // 检查是否有多余的代码块需要删除
            $oldIfBlock = "if (\$isLoggedIn) {
    try {
        // 连接数据库
        \$dsn = \"mysql:host=\".DB_HOST.\";dbname=\".DB_NAME.\";charset=\".DB_CHARSET;
        \$db = new PDO(\$dsn, DB_USERNAME, DB_PASSWORD);
        \$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // 获取管理员信息
        \$stmt = \$db->prepare(\"SELECT * FROM \" . DB_PREFIX . \"users WHERE id = ? AND role = 'admin'\");
        \$stmt->execute([\$_SESSION['admin_user_id']]);
        \$admin = \$stmt->fetch(PDO::FETCH_ASSOC);
        
        // 如果用户不存在或不是管理员，注销会话
        if (!\$admin) {
            unset(\$_SESSION['admin_user_id']);
            unset(\$_SESSION['admin_username']);
            header('Location: login.php');
            exit;
        }
    } catch (PDOException \$e) {
        die(\"数据库连接失败: \" . \$e->getMessage());
    }
}";
            
            $newContent = str_replace($oldIfBlock, "}", $newContent);
            
            file_put_contents($headerFile, $newContent);
            
            // 检查语法
            $syntaxCheck = checkPhpSyntax($headerFile);
            if ($syntaxCheck['valid']) {
                $results[] = "成功修改 header.php 以使用 DatabaseHelper";
            } else {
                // 恢复备份
                copy($backup, $headerFile);
                $results[] = "无法修改 header.php：语法错误，已恢复备份";
                $success = false;
            }
        } else {
            $results[] = "无法定位header.php中的管理员验证部分，请手动修改";
            $success = false;
        }
    } else {
        $results[] = "header.php 已支持 DatabaseHelper";
    }
} else {
    $results[] = "文件 header.php 不存在";
    $success = false;
}

// 创建CSS文件夹（如果不存在）
$cssDir = __DIR__ . '/css';
if (!is_dir($cssDir)) {
    if (mkdir($cssDir, 0755)) {
        $results[] = "已创建 css 目录";
    } else {
        $results[] = "无法创建 css 目录";
        $success = false;
    }
}

// 创建admin.css文件（如果不存在）
$cssFile = $cssDir . '/admin.css';
if (!file_exists($cssFile)) {
    $cssContent = <<<EOT
/* KidsMind 管理后台样式 */
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background-color: #f8f9fa;
}

.avatar-sm {
    width: 40px;
    height: 40px;
    object-fit: cover;
}

.card {
    margin-bottom: 1.5rem;
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
}

.card-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid rgba(0, 0, 0, 0.125);
    font-weight: 600;
}

/* 仪表盘卡片 */
.card .display-4 {
    font-size: 3rem;
}

/* 表格样式 */
.table th {
    background-color: #f8f9fa;
    font-weight: 600;
}

/* 删除按钮 */
.btn-delete {
    color: #dc3545;
    background-color: transparent;
    border: none;
}

.btn-delete:hover {
    color: #bd2130;
}

/* 导航栏下拉菜单 */
.dropdown-menu {
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}

/* 登录页面 */
.bg-light {
    background-color: #f8f9fa;
}
EOT;
    file_put_contents($cssFile, $cssContent);
    $results[] = "已创建 admin.css 文件";
}

// 添加测试数据库连接的脚本
$testDbFile = __DIR__ . '/test_db.php';
if (!file_exists($testDbFile)) {
    $testDbContent = <<<EOT
<?php
// 显示所有错误
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 引入DatabaseHelper类
require_once 'includes/DatabaseHelper.php';

// 测试数据库连接
try {
    // 获取数据库实例
    \$db = Database::getInstance();
    
    // 尝试执行简单查询
    \$tables = \$db->fetchAll("SHOW TABLES");
    
    // 输出结果
    \$success = true;
    \$message = "数据库连接和查询成功！";
    \$result = [
        'tables' => \$tables,
        'database_class' => get_class(\$db),
        'connection_active' => (\$db->getConnection() instanceof PDO)
    ];
} catch (Exception \$e) {
    // 捕获异常
    \$success = false;
    \$message = "错误: " . \$e->getMessage();
    \$result = [
        'error_code' => \$e->getCode(),
        'trace' => \$e->getTraceAsString()
    ];
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KidsMind - 数据库测试</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow">
                    <div class="card-header <?php echo \$success ? 'bg-success' : 'bg-danger'; ?> text-white">
                        <h4 class="mb-0">KidsMind 数据库测试</h4>
                    </div>
                    <div class="card-body">
                        <div class="alert <?php echo \$success ? 'alert-success' : 'alert-danger'; ?>">
                            <strong><?php echo \$message; ?></strong>
                        </div>
                        
                        <?php if (\$success): ?>
                            <h5>数据库信息:</h5>
                            <ul class="list-group mb-4">
                                <li class="list-group-item">使用类: <?php echo \$result['database_class']; ?></li>
                                <li class="list-group-item">连接状态: <?php echo \$result['connection_active'] ? '活跃' : '未连接'; ?></li>
                            </ul>
                            
                            <h5>数据库表:</h5>
                            <table class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>表名</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach (\$result['tables'] as \$table): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars(reset(\$table)); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php else: ?>
                            <h5>错误信息:</h5>
                            <pre class="bg-light p-3"><?php echo htmlspecialchars(print_r(\$result, true)); ?></pre>
                        <?php endif; ?>
                        
                        <div class="mt-4">
                            <a href="index.php" class="btn btn-primary">返回控制台</a>
                            <a href="fix_database_class.php" class="btn btn-secondary">重新运行修复工具</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
EOT;
    file_put_contents($testDbFile, $testDbContent);
    $results[] = "已创建数据库测试脚本 test_db.php";
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KidsMind - 修复数据库类</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow">
                    <div class="card-header bg-success text-white">
                        <h4 class="mb-0">KidsMind 数据库类修复工具</h4>
                    </div>
                    <div class="card-body">
                        <h5 class="card-title mb-4">修复结果</h5>
                        
                        <?php foreach ($results as $result): ?>
                            <div class="alert alert-info"><?php echo $result; ?></div>
                        <?php endforeach; ?>
                        
                        <div class="alert <?php echo $success ? 'alert-success' : 'alert-danger'; ?>">
                            <?php if ($success): ?>
                                <strong>修复完成！</strong> 所有页面现在应该可以正常访问。
                            <?php else: ?>
                                <strong>部分修复未完成！</strong> 请检查错误并手动修复。
                            <?php endif; ?>
                        </div>
                        
                        <div class="mt-4">
                            <p><strong>下一步操作：</strong></p>
                            <ol>
                                <li>首先访问 <a href="test_db.php">数据库测试脚本</a> 检查数据库连接</li>
                                <li>然后访问 <a href="index.php">管理后台首页</a> 检查是否正常</li>
                                <li>如果仍有问题，检查服务器错误日志</li>
                            </ol>
                        </div>
                        
                        <div class="mt-4">
                            <a href="test_db.php" class="btn btn-primary">测试数据库连接</a>
                            <a href="index.php" class="btn btn-success">返回控制台</a>
                            <a href="login.php" class="btn btn-secondary">返回登录页</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html> 